package com.jy.appmarket.activity;

import com.jy.app.market.idata.data.Login;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.dialog.WaitDialog;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.SetPasswdNetEngine;
import com.jy.appmarket.network.resultdata.SetPasswdResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.utils.CryptoUtil;
import com.jy.appmarket.utils.LoginUtil;
import com.jy.appmarket.utils.StringUtil;
import com.umeng.analytics.MobclickAgent;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SetPasswdActivity extends Activity implements NetTaskListener{
	public static final String EXTRA_NAME = "name";
	public static final String EXTRA_PHONE_NUM = "phone_num";
	public static final String EXTRA_TYPE = "type";
	public static final String EXTRA_VERIFY_CODE = "verify_code";
	
	private NetTask mNetTask;
	private WaitDialog mWaitDialog;
	private EditText mPasswdEdit;
	
	private String mName;
	private String mPhoneNum;
	private String mType;
	private String mVerifyCode;
	private String mPasswd;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_passwd);
		
		getExtras();
		initTitle();
		initViews();
	}

	private void getExtras() {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				mName = extras.getString(EXTRA_NAME);
				mPhoneNum = extras.getString(EXTRA_PHONE_NUM);
				mType = extras.getString(EXTRA_TYPE);
				mVerifyCode = extras.getString(EXTRA_VERIFY_CODE);
			}
		}
	}
	
	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(mName);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
	
	private void initViews() {
		mPasswdEdit = findViewById(R.id.passwd_edit);
	}
	
	private void bindPhone() {
		mPasswd = mPasswdEdit.getText().toString();

		if (TextUtils.isEmpty(mPasswd)) {
			Toast.makeText(this, R.string.please_input_password,
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (StringUtil.hasSpaceChar(mPasswd)) {
			Toast.makeText(this, R.string.password_not_has_space,
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		if (mPasswd.length() < 6) {
			Toast.makeText(this, R.string.password_format_error,
					Toast.LENGTH_SHORT).show();
			return;
		}
		
		showWaitDialog();
		SetPasswdNetEngine engine = new SetPasswdNetEngine(mPhoneNum, CryptoUtil.md5(mPasswd), mType, mVerifyCode);
		mNetTask = new NetTask(this, engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.register_menu, menu);
		final MenuItem item = menu.findItem(R.id.action_next);
		item.setTitle(R.string.next);
		LinearLayout itemLayout = (LinearLayout) item.getActionView();
		TextView title = itemLayout.findViewById(R.id.menu_title);
		title.setText(R.string.next);
		
		itemLayout.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
            	 SetPasswdActivity.this.onOptionsItemSelected(item);
             }
         });
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.action_next:
			bindPhone();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		dismissWaitDialog();
		SetPasswdResult resultData = (SetPasswdResult) engine.getResultData();
		if (!resultData.isOK()) {
			if (resultData.getStatus() == 461) {
				//如果返回461为验证码已经失效，客户端需要关闭设置密码页面，用户需要从新获取验证码
				backToGetVerifyCode();
			} else {
				String message = resultData.getMessage();
				if (!TextUtils.isEmpty(message)) {
					Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(this, R.string.set_passwd_error, Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			// 如果是注册，设置为登录状态
			if ("register".equals(mType)) {
				Login login = resultData.getLogin();
				AppMarketApplication.setLogin(login);
				LoginUtil.saveLogin(this, login);
				
				Intent intent = new Intent(this, ModifyUserInfoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(ModifyUserInfoActivity.EXTRA_NAME, "完善个人资料（3/3）");
				bundle.putBoolean(ModifyUserInfoActivity.EXTRA_IS_SHOW_MENU, true);
				intent.putExtras(bundle);
				startActivity(intent);
			} else if ("forget_password".equals(mType)) {
				Toast.makeText(this, "重置密码成功", Toast.LENGTH_SHORT).show();
			} else if ("bind_phonenum".equals(mType)) {
				Toast.makeText(this, "绑定手机成功", Toast.LENGTH_SHORT).show();
				Login login = AppMarketApplication.getLogin();
				login.setPhoneNum(mPhoneNum);
				LoginUtil.saveLogin(this, login);
			}
			finish();
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		dismissWaitDialog();
		Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		dismissWaitDialog();
	}
	
	private void backToGetVerifyCode() {
		if ("register".equals(mType)) {
			Intent intent = new Intent(this, CheckVerifyCodeActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString(CheckVerifyCodeActivity.EXTRA_NAME, "手机注册（1/3）");
			bundle.putString(CheckVerifyCodeActivity.EXTRA_TYPE, "register");
			bundle.putString(CheckVerifyCodeActivity.EXTRA_PHONE_NUM, mPhoneNum);
			bundle.putBoolean(CheckVerifyCodeActivity.EXTRA_NEED_GET_VERIFY_CODE, true);
			intent.putExtras(bundle);
			startActivity(intent);
		} else if ("forget_password".equals(mType)) {
			Intent intent = new Intent(this, ForgetPasswdActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString(ForgetPasswdActivity.EXTRA_PHONE_NUM, mPhoneNum);
			intent.putExtras(bundle);
			startActivity(intent);
		} else if ("bind_phonenum".equals(mType)) {
			Intent intent = new Intent(this, CheckVerifyCodeActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString(CheckVerifyCodeActivity.EXTRA_NAME, "绑定手机号（2/3））");
			bundle.putString(CheckVerifyCodeActivity.EXTRA_TYPE, "bind_phonenum");
			bundle.putString(CheckVerifyCodeActivity.EXTRA_PHONE_NUM, mPhoneNum);
			bundle.putBoolean(CheckVerifyCodeActivity.EXTRA_NEED_GET_VERIFY_CODE, true);
			intent.putExtras(bundle);
			startActivity(intent);
		}
		Toast.makeText(this, R.string.verify_code_invalid, Toast.LENGTH_SHORT).show();
		finish();
	}
	
	private void showWaitDialog(){
		if (mWaitDialog == null) {
			mWaitDialog = new WaitDialog(this);
			mWaitDialog.setCanceledOnTouchOutside(false);
			mWaitDialog.setCancelable(false);
		}
		if (mWaitDialog.isShowing()) {
			return;
		}
		mWaitDialog.showTitle("请稍候...").show();
	}
	
	private void dismissWaitDialog(){
		if (mWaitDialog != null) {
			mWaitDialog.dismiss();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
		dismissWaitDialog();
		super.onDestroy();
	}

}
